package com.example.online.servlet;

import com.example.online.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;


@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private final UserService service= new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //获取前端表单提交的数据
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String pwd = req.getParameter("pwd");

//        System.out.println("他奶奶的");

//        return;
        //判断用户名是否已被使用
        if(service.isExistByName(name) > 0){
            req.setAttribute("Register",0);
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }

         //判断手机号是否已被使用
        if(service.isExistByPhone(phone) > 0){
            req.setAttribute("Register",1);
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }


        //校验通过，设置弹窗，跳转登陆界面
        req.setAttribute("Login",0);
        service.insert(phone,name,pwd);//将用户写入数据库
        req.getRequestDispatcher("login.jsp").forward(req,resp);

    }
}
